package com.lc.reader.ui.viewmodel

import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import com.lc.reader.data.model.Book
import com.lc.reader.data.repository.BookRepository
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch

class ReaderViewModel(
    private val bookRepository: BookRepository
) : ViewModel() {
    
    private val _bookInfo = MutableStateFlow<Book?>(null)
    val bookInfo: StateFlow<Book?> = _bookInfo
    
    private val _currentPage = MutableStateFlow<String?>(null)
    val currentPage: StateFlow<String?> = _currentPage
    
    var currentPageNumber = 1
        private set
    var totalPages = 1
        private set
    
    fun loadBook(bookId: Long) {
        viewModelScope.launch {
            val book = bookRepository.getBookById(bookId)
            _bookInfo.value = book
            
            book?.let {
                currentPageNumber = it.currentPage
                totalPages = it.totalPages
                loadPageContent(it, currentPageNumber)
            }
        }
    }
    
    fun nextPage() {
        val book = _bookInfo.value ?: return
        if (currentPageNumber < totalPages) {
            currentPageNumber++
            loadPageContent(book, currentPageNumber)
            updateReadingProgress(book.id, currentPageNumber)
        }
    }
    
    fun previousPage() {
        val book = _bookInfo.value ?: return
        if (currentPageNumber > 1) {
            currentPageNumber--
            loadPageContent(book, currentPageNumber)
            updateReadingProgress(book.id, currentPageNumber)
        }
    }
    
    private fun loadPageContent(book: Book, pageNumber: Int) {
        viewModelScope.launch {
            // 暂时使用模拟内容，实际应用中需要实现文件解析逻辑
            _currentPage.value = "第${pageNumber}页内容 - 这是示例内容，实际应用中需要从文件中读取。"
        }
    }
    
    private fun updateReadingProgress(bookId: Long, pageNumber: Int) {
        viewModelScope.launch {
            val progress = pageNumber.toFloat() / totalPages
            val lastReadTime = System.currentTimeMillis()
            bookRepository.updateReadingProgress(bookId, pageNumber, lastReadTime, progress)
        }
    }
}

// 简单的ViewModelFactory
class ReaderViewModelFactory(
    private val bookRepository: BookRepository
) : ViewModelProvider.Factory {
    
    override fun <T : ViewModel> create(modelClass: Class<T>): T {
        if (modelClass.isAssignableFrom(ReaderViewModel::class.java)) {
            @Suppress("UNCHECKED_CAST")
            return ReaderViewModel(bookRepository) as T
        }
        throw IllegalArgumentException("Unknown ViewModel class")
    }
}
